from qiniu import Auth, put_file
import uuid
from PIL import Image  # pip install pillow
import io, os


def upload(img):
    _img = img.read()
    size = len(_img) / (1024 * 1024)  # 上传图片的大小 M单位
    print(size)
    image = Image.open(io.BytesIO(_img))
    key = str(uuid.uuid1()).replace('-', '') + '.' + image.format
    access_key = 'W5LZ0s2E9P8E4b7k-TqhPQBvCKqaHnwbIO_3FDfA'
    secret_key = 'tDaH0FEcEN_RpNPTjsZ3FaF9rPnQ_yLWZndmI6Ya'
    q = Auth(access_key, secret_key)
    bucket_name = 'gongnanxiong'
    token = q.upload_token(bucket_name, key, 3600, )
    name = 'upfile.{0}'.format(image.format)  # 获取图片后缀（图片格式）
    if size > 1:
        x, y = image.size
        im = image.resize((int(x / 1.73), int(y / 1.73)), Image.ANTIALIAS)  # 等比例压缩 1.73 倍
        print('压缩')
    else:
        print('不压缩')
        im = image
    # im = image
    im.save('./media/' + name)  # 在根目录有个media文件
    path = './media/' + name
    # up = im.read()
    put_file(token, key, path)
    url = 'http://gongnanxiong.top/{}'.format(key)
    if os.path.exists(path):
        os.remove(path)
        print("%s-->已经删除", path)
    return url
